#include "Skybox.h"

Skybox::Skybox() : BaseIndexedGraphicalEntity()
{
	SkyboxTexture = NULL;
}

Skybox::Skybox( IDirect3DDevice9 *nDevice) : BaseIndexedGraphicalEntity(nDevice)
{
	SkyboxTexture = NULL;
	CreateCube(D3DXVECTOR3(5000.f, 5000.f, 5000.f));
}

Skybox::~Skybox( void )
{
	if(SkyboxTexture)
		SkyboxTexture->Release();
}

HRESULT Skybox::LoadTextureFromFile(std::string filename)
{
	HRESULT hr = D3DXCreateTextureFromFile(Device, filename.c_str(), &SkyboxTexture);

	return hr;
}

void Skybox::Update( float dt)
{
	BaseIndexedGraphicalEntity::Update(dt);
}

void Skybox::Render( void )
{
	Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW);
	Device->SetTexture(0, SkyboxTexture);
	BaseIndexedGraphicalEntity::Render();
	Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
}

IDirect3DTexture9* Skybox::GetTexture( void )
{
	return SkyboxTexture;
}

bool Skybox::CreateCube(D3DXVECTOR3 HalfVector)
{
	if(VertexBuffer)
		VertexBuffer->Release();
	if(IndexBuffer)
		IndexBuffer->Release();

	gd3dDevice->CreateVertexBuffer(8 * sizeof(Vertex), D3DUSAGE_WRITEONLY, 0, D3DPOOL_MANAGED, &VertexBuffer, 0);
	gd3dDevice->CreateIndexBuffer(36 * sizeof(int*), D3DUSAGE_WRITEONLY, D3DFMT_INDEX32, D3DPOOL_MANAGED, &IndexBuffer, 0);

	HRESULT hrs;
	Vertex* v = NULL;
	
	D3DXCOLOR tempColor = D3DCOLOR_XRGB(rand(),rand(),rand());

	hrs = (VertexBuffer->Lock(0, 0, (void**)&v, 0));
	
	//1,1,1
	v[0] = Vertex(( HalfVector.x), HalfVector.y, ( HalfVector.z), tempColor, 0.0, 0.0);
	//1,1,-1
	v[1] = Vertex((HalfVector.x), HalfVector.y, (-HalfVector.z), tempColor, 0.0, 5.0);
	//-1,1,1
	v[2] = Vertex((-HalfVector.x), HalfVector.y, ( HalfVector.z), tempColor, 5.0, 0.0);
	//-1,1,-1
	v[3] = Vertex((-HalfVector.x), HalfVector.y, (-HalfVector.z), tempColor, 5.0, 5.0);

	//1,-1,1
	v[4] = Vertex(( HalfVector.x), -HalfVector.y, ( HalfVector.z), tempColor, 5.0, 5.0);
	//-1,-1,1
	v[5] = Vertex((-HalfVector.x), -HalfVector.y, ( HalfVector.z), tempColor, 0.0, 5.0);
	//1,-1,-1
	v[6] = Vertex(( HalfVector.x), -HalfVector.y, (-HalfVector.z), tempColor, 5.0, 0.0);
	//-1,-1,-1
	v[7] = Vertex((-HalfVector.x), -HalfVector.y, (-HalfVector.z), tempColor, 0.0, 0.0);

	numVertices = 8;

	hrs = (VertexBuffer->Unlock());
	hrs = 0;

	unsigned int Indices[] = 
	{
			//1
			3, 1, 7,
			7, 1, 6,
			//2
			2, 3, 5,
			5, 3, 7,
			//3
			4, 0, 5,
			5, 0, 2,
			//4
			6, 1, 4,
			4, 1, 0,
			//5
			2, 0, 3,
			3, 0, 1,
			//6
			6, 4, 7,
			7, 4, 5

	};

	void *pVoid;

	hrs = (IndexBuffer->Lock(0, 0, (void**)&pVoid, 0));

	memcpy(pVoid, Indices, sizeof(Indices));

	hrs = (IndexBuffer->Unlock());

	numIndices = 36;
	return true;

}